package org.duang.handles;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpHeaders;
import org.duang.http.util.HttpUtil;
import org.duang.kit.ToolsKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 是否安全请求处理器
 * 
 * @author laotang
 */
public class DuangRequestHandle implements IHandle {

	private static Logger logger = LoggerFactory.getLogger(DuangRequestHandle.class);
	private static final String responseErrorMessage = "request %s is null, quit...";
	private static final Set<String> uriSet = new HashSet<String>();

	public DuangRequestHandle() {

	}

	@SuppressWarnings("static-access")
	public DuangRequestHandle(Set<String> uriSet) {
		this.uriSet.addAll(uriSet);
	}

	@Override
	public void execute(String target, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!ToolsKit.isSecurityUrl(target)) {
			return;
		}

		if (!uriSet.isEmpty() && uriSet.contains(target)) {
			String userAgentStr = request.getHeader(HttpHeaders.USER_AGENT);
			if (ToolsKit.isEmpty(userAgentStr)) {
				logger.warn(String.format(responseErrorMessage, HttpHeaders.USER_AGENT));
				response.getWriter().print(String.format(responseErrorMessage, HttpHeaders.USER_AGENT));
				return;
			}
			String versionString = userAgentStr.substring(userAgentStr.indexOf("/")+1, userAgentStr.indexOf("(")).replace(".","");
			int version = 0;
			try{version = Integer.parseInt(versionString) ;} catch(Exception e) {};
			if(version == 0){
				logger.warn(String.format(responseErrorMessage, "version"));
				response.getWriter().print(String.format(responseErrorMessage, "version"));
				return;
			}
			if (version >= 200) {
				String authStr = request.getHeader(HttpHeaders.AUTHORIZATION);
				if (ToolsKit.isEmpty(authStr)) {
					logger.warn(String.format(responseErrorMessage, HttpHeaders.AUTHORIZATION));
					response.getWriter().print(String.format(responseErrorMessage, HttpHeaders.AUTHORIZATION));
					return;
				}
				long requestTime = Long.parseLong(request.getHeader(HttpHeaders.DATE));
				if ((System.currentTimeMillis() - requestTime) > 10000) {
					logger.debug("the request time is more than 10 seconds");
					return;
				}
				if (!HttpUtil.isDuangAuthorizAtionSignKey(authStr)) {
					return;
				}
			} else {
				if(!HttpUtil.isDuangUserAgentSignKey(userAgentStr)){
					return;
				}
			} 
		}
	}

}
